<?php

namespace app\common\model\mycurrency;

use think\Exception;
use think\Model;


class AgentProfit extends Model
{

    

    

    // 表名
    protected $name = 'mycurrency_agent_profit';

    /**
     * 处理分销逻辑
     * @param int $agent_id 代理商id
     * @param int $paid_dlready 分销基数
     * @param int $separated 起始分成比例
     * @param array $data 扩展数据
     */
    public static function divideInto($agent_id,$paid_dlready,$separated = 0,$data=[]){
        $agent = Agent::where(['id' => $agent_id,'deletetime' => null])->find();
        if($agent){
            if ($agent->status == Agent::STATUS_ZHENGCHENG){
                $div_proportion = $agent->divideinto - $separated;
                $div_proportion = $div_proportion < 0 ? 0 : $div_proportion;
                $actual_income = sprintf("%.2f",($paid_dlready / 100) * $div_proportion) ;
                $increase = [
                    'agent_id' => $agent->id,
                    'tra_amount' => $paid_dlready,
                    'div_proportion' => $div_proportion,
                    'actual_income' => $actual_income,
                    'memo' => '租赁订单收益分成',
                    'createtime' => time()
                ];
                $increase = array_merge($increase,$data);
                $profit = self::create($increase);
                AgentMoneylog::moneyChange(
                    $agent->id,
                    $actual_income,
                    AgentMoneylog::TYPE_YONGHUXIAOFEI,
                    [
                        'profit_id' => $profit->id,
                    ]
                );
                $separated += $div_proportion;
            }
            if ($agent->pid != 0 && $agent->pid != null){
                self::divideInto($agent->pid,$paid_dlready,$separated,$data);
            }
        }
    }



    public function getCreatetimeAttr($value){
        return $value != null ? date('Y-m-d H:i:s', $value) : '';
    }
    

    public function agent()
    {
        return $this->belongsTo('app\admin\model\mycurrency\Agent', 'agent_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

}
